package com.nowcoder.community.util;

import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.util.Map;
import java.util.UUID;

/**
 * @author 韩
 * @version 1.0
 */
public class CommunityUtil {

    //生成随机字符串
    public static String generateUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    //MD5加密
    //hello  ->  abc123def456
    //hello + 随即字符串  -> abc123def456
    public static String md5(String key) {
        if (StringUtils.isBlank(key)) {//判断null 或者""
            return null;
        } else {
            return DigestUtils.md5DigestAsHex(key.getBytes());
        }
    }

    /**
     * 将传入的信息转换成json字符串
     * @param code:相应状态
     * @param msg:状态对应信息
     * @param map:回传信息
     * @return : json字符串
     */
    public static String getJsonString(int code, String msg, Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("msg", msg);
        if (map != null) {
            for (String key : map.keySet()) {
                json.put(key, map.get(key));
            }
        }
        return json.toString();
    }

    public static String getJsonString(int code, String msg) {
        return getJsonString(code, msg, null);
    }

    public static String getJsonString(int code) {
        return getJsonString(code, null, null);
    }

}
